import datetime

import utils.jsonData as JsonData
from peewee import JOIN, fn
from playhouse.shortcuts import model_to_dict
from model import Process as ModelProcess
from model import Project as ModelProject

from entity.Prosumer import PRODUCER
from utils.prosumer_task import *


def query_process():
    """查询所有本地进程信息"""
    _res = ModelProcess.Process.select()
    _list = []
    for i in _res:
        _dict = model_to_dict(i)
        if _dict["project_id"] is None:
            _dict["name"] = False
        else:
            _dict["name"] = _dict["project_id"]["name"]
        _list.append(_dict)
    PRODUCER.push("1.1.1.1", update_process_status_task, _list)
    return JsonData.JsonData().success_data(msg="查询项目信息成功", data=_list)


def update_process_status(process_id, value):
    """根据本地进程更新状态"""
    ModelProcess.Process.update({
        ModelProcess.Process.status: value
    }).where(
        ModelProcess.Process.id == process_id
    ).execute()


def addProcess(process_dict):
    """添加本地进程信息"""
    if queryProcessIsExistsByIpAndPort(process_dict["ip"], process_dict["port"]):
        return JsonData.JsonData().error(code="1006", msg="ip和port组合已存在，不用重复添加")
    _res = ModelProcess.Process(
        ip=process_dict["ip"],
        port=process_dict["port"],
        create_time=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    ).save()
    if _res:
        return JsonData.JsonData().success_data(msg="添加成功")
    return JsonData.JsonData().error(code="1006", msg="上传失败，服务器好像出现问题了！请重试")


def queryProcessIsExistsByIpAndPort(ip, port):
    """根据ip和port查询数据库是否存在，存在返回True，反之False"""
    _res = ModelProcess.Process.select().where((ModelProcess.Process.ip == ip) & (ModelProcess.Process.port == port))
    for i in _res:
        return True
    return False


def delete_process_by_id(process_id):
    """根据id删除数据"""
    _res = ModelProcess.Process.delete().where(ModelProcess.Process.id == process_id).execute()
    if not _res:
        return JsonData.JsonData.JsonData().error(code="1005", msg="删除失败，找不到这个项目编号")
    return JsonData.JsonData().success_data(msg="删除成功")


def update_process(process_id, _json):
    """根据id更新数据"""
    _res = ModelProcess.Process.update({
        ModelProcess.Process.ip: _json["ip"],
        ModelProcess.Process.port: _json["port"],
        ModelProcess.Process.create_time: datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }).where(
        ModelProcess.Process.id == process_id).execute()
    if not _res:
        return JsonData.JsonData.JsonData().error(code="1008", msg="更新失败")
    return JsonData.JsonData().success_data(msg="更新成功")


def query_process_by_id(process_id):
    """根据id获取本地进程信息"""
    ip = ""
    port = ""
    create_time = ""
    status = ""
    project_id = ""
    try:
        for i in ModelProcess.Process.select().where(ModelProcess.Process.id == process_id):
            ip = i.ip
            port = i.port
            create_time = i.create_time
            status = i.status
            project_id = i.project_id
    except Exception:
        return JsonData.JsonData().error(code="1005", msg="查询失败")
    if ip == "" or ip is None:
        return JsonData.JsonData().error(code="1005", msg="查询失败，找不到这个项目编号")
    _res = {
        "ip": ip,
        "port": port,
        "create_time": create_time,
        "status": status,
        "project_id": project_id.__dict__["__data__"]
    }
    return JsonData.JsonData().success_data(msg="查询项目信息成功", data=[_res])
